# -*- coding: utf-8 -*-
import os
from flask import Flask, send_from_directory
from waitress import serve
from config import Config
from dao.user_dao import db
from controller.auth_controller import auth_bp
from controller.register_controller import register_bp
from controller.classmgr_controller import classmgr_bp
from controller.teachermgr_controller import teachermgr_bp
from controller.studentmgr_controller import studentmgr_bp
from controller.group_controller import group_bp
from controller.exam_controller import exam_bp
from controller.point_controller import point_bp
from controller.message_controller import message_bp
from controller.user_contoller import user_bp
from filter.auth import auth_required
from werkzeug.routing import BaseConverter

def create_app():
    app = Flask(__name__, static_folder='dist')
    app.config.from_object(Config)
    
    # 初始化数据库
    db.init_app(app)
    
    # 注册蓝图
    app.register_blueprint(auth_bp, url_prefix='/api/auth')
    app.register_blueprint(register_bp, url_prefix='/api/register')
    app.register_blueprint(classmgr_bp, url_prefix='/api/classmgr')
    app.register_blueprint(teachermgr_bp, url_prefix='/api/teachermgr')
    app.register_blueprint(studentmgr_bp, url_prefix='/api/studentmgr')
    app.register_blueprint(group_bp, url_prefix='/api/group')
    app.register_blueprint(exam_bp, url_prefix='/api/exam')
    app.register_blueprint(point_bp, url_prefix='/api/point')
    app.register_blueprint(message_bp, url_prefix='/api/message')
    app.register_blueprint(user_bp, url_prefix='/api/user')
    
    # 测试需要token的接口
    @app.route('/api/test', methods=['GET'])
    @auth_required
    def test():
        from flask import g
        return {
            'user_id': g.user_id,
            'role': g.role,
            'name': g.name
        }
    
    # frontend 挂载
    # 处理assets文件夹下的静态资源（js、css等）
    @app.route('/assets/<path:path>')
    def send_assets(path):
        # 指向dist/assets目录
        assets_dir = os.path.join(app.static_folder, 'assets')
        return send_from_directory(assets_dir, path)

    # 处理根路径和所有其他路由，返回index.html支持Vue前端路由
    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def catch_all(path):
        # 否则返回index.html支持前端路由
        return send_from_directory(app.static_folder, 'index.html')
    
    # 自定义转换器：匹配所有以.svg结尾的路径（包括子目录）
    class SvgConverter(BaseConverter):
        # 正则表达式：匹配任意字符（包括/），最后以.svg结尾
        regex = r'.+\.svg$'

    # 注册转换器
    app.url_map.converters['svg'] = SvgConverter

    # 路由：匹配所有以.svg结尾的请求（如 /logo.svg、/assets/icons/icon.svg 等）
    @app.route('/<svg:path>')
    def send_svg(path):
        # 拼接dist目录下的完整路径
        svg_path = os.path.join(app.static_folder, path)
        # 安全校验：确保请求的文件确实在dist目录下（防止路径穿越攻击）
        if not svg_path.startswith(os.path.abspath(app.static_folder)):
            return "Invalid path", 403
        # 拆分目录和文件名（send_from_directory需要分离目录和文件名）
        dir_name = os.path.dirname(path)
        file_name = os.path.basename(path)
        return send_from_directory(os.path.join(app.static_folder, dir_name), file_name)
        
    return app

if __name__ == '__main__':
    app = create_app()
    # 使用waitress启动服务
    serve(app, host='0.0.0.0', port=5000)